package com.coder4j.starter.tools.util;

import com.alibaba.fastjson.JSON;
import com.coder4j.starter.tools.vo.RegionVO;

/**
 * 地址处理工具
 * 将文本型的地址按照省、市、区三级行政区划拆分
 * @author Keller
 * @date 2023-03-09 16:24:30
 */
public class AddressUtils {

    public static void main(String[] args) {
        RegionVO region = converRegion("江西省南昌市新建区金桥乡罗坪村罗家坪自然村");
        System.out.println(JSON.toJSONString(region));
    }

    /**
     * 省级行政单位：省、直辖市、特别行政区
     */
    private static final String[] Province = {"省", "市", "区"};

    private static final String[] City = {"市","区","州", "盟"};

    private static final String[] County = {"县","市", "区", "旗", "域",  "岛"};

    /**
     * 处理详细地址拆分省 市 区 地址的转换关系
     *
     * @param detailAddress
     * @return
     */
    public static RegionVO converRegion(
            String detailAddress) {
        RegionVO region = new RegionVO();
        try {

            String tempStr = detailAddress;
            int provinceIdx = processProvince(tempStr);
            if (provinceIdx > -1) {
                region.setProvince(tempStr.substring(0, provinceIdx + 1));
                tempStr = tempStr.substring(provinceIdx + 1);
            }

            int cityIdx = processCity(tempStr);
            if (cityIdx > -1) {
                region.setCity(tempStr.substring(0, cityIdx + 1));
                tempStr = tempStr.substring(cityIdx + 1);
            }

            int countyIdx = processCounty(tempStr);
            if (countyIdx > -1) {
                region.setDistrict(tempStr.substring(0, countyIdx + 1));
                tempStr = tempStr.substring(countyIdx + 1);
            }
            region.setStreet(tempStr);
        } catch (Exception e) {
            // 报错就直接返回即可。无法正常转义
        }
        return region;
    }

    /**
     * (?<province>[^省]+自治区|.*?省|.*?行政区|.*?市)
     */
    private static int processProvince(String address) {
        int index = -1;
        for (String item : Province) {
            index = address.indexOf(item);
            if (index > -1) {
                return index;
            }
        }
        return index;
    }

    // (?<city>[^市]+自治州|.*?地区|.*?行政单位|.+盟|市辖区|.*?市|.*?县)
    private static int processCity(String address) {
        int index = -1;
        for (String item : City) {
            index = address.indexOf(item);
            if (index > -1) {
                return index;
            }
        }
        return index;
    }

    // (?<county>[^县]+县|.+区|.+市|.+旗|.+海域|.+岛)
    private static int processCounty(String address) {
        int index = -1;
        for (String item : County) {
            index = address.indexOf(item);
            if (index > -1) {
                return index;
            }
        }
        return index;
    }
}
